package com.study.send;

import com.study.Entity.Command;
import com.study.Entity.MqMessage;
import com.study.constant.Constants;
import com.study.netty2.ChannelMap;
import com.study.service.RedisService;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author mjy
 * @date 2021/12/08
 * @description
 */
public abstract class Sender {

    @Autowired
    private RedisService redisService;

    public  boolean send(Command command) {
        if (command==null){
            return false;
        }
        String imei = command.getImei();
        Integer status = command.getStatus();
        //获取管道
        Channel channel = ChannelMap.get(imei);
        boolean flag = false;
        if (channel!=null){
            //将指令写入管道
            channel.writeAndFlush(command.getContent());
            //设置指令最后发送时间
            command.setLastSendTime(System.currentTimeMillis());
            //设置指令发送状态为已发送
            command.setStatus(Constants.COMMAND_NOT_RESPONSE);
            flag=true;
        }else {//记录发送失败
            flag=false;
            command.setLastSendTime(System.currentTimeMillis());
            //设置指令发送状态为已发送
            command.setStatus(Constants.COMMAND_SEND_FAILED);
        }
        //查看指令是否需要保存，或者说发送失败
        if (flag||Constants.COMMAND_NEED_SAVE==status){
            redisService.saveCommand(imei,command.getCmd().concat("-").concat(command.getCommandNumber()),command);
        }
        return flag;
    }

    public abstract Command dealMessage(MqMessage mqMessage);

}
